<template>
  <div class="describe">
    <div class="describe-card">
      <div class="describe-header">
        {{ describeContent?.nodeName }}
      </div>
      <div class="describe-content">
        <a-descriptions :data="descData" bordered size="large" :column="1" layout="vertical" />
      </div>
      <!--<div class="describe-footer" v-if="nodeForm.list.length > 0">
        <a-row>
          <a-date-picker
            show-time
            v-model="time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="changeTime"
            style="width: 100%"
          />
          <a-popconfirm
            content="是否生成健康评估报告?"
            type="warning"
            ok-text="是"
            cancel-text="否"
            @ok="handleOk"
            @cancel="handleSubmit"
          >
            <a-button class="describe-btn">健康度计算</a-button>
          </a-popconfirm>
        </a-row>
      </div>-->
    </div>
  </div>
  <!-- 弹框 下载健康评估报告 -->
  <a-modal
    v-model:visible="nodeForm.visible"
    title="健康评估报告"
    title-align="start"
    cancel-text="关闭"
    ok-text="下载报告"
    @before-ok="handleBeforeOk"
    @cancel="handleCancel"
    width="45%"
    modal-class="formModal"
    :mask-closable="false"
  >
    <a-row class="grid" id="pdfDom">
      <a-col :span="12">
        <p><i>卫星名称：</i>{{ describeContent?.nodeName }}</p>
      </a-col>
      <a-col :span="12">
        <p><i>评估时间：</i>{{ time }}</p>
      </a-col>
      <a-col :span="24">
        <p>本次评估结果</p>
        <Table ref="mergeTableRef" :columns="nodeForm.columns" :tableList="nodeForm.dataList"></Table>
      </a-col>
      <a-col :span="24">
        <p>本次评估故障次数趋势结果</p>
        <div id="report-charts" ref="typeCharts"></div>
      </a-col>
    </a-row>
  </a-modal>
  <!-- 弹框 下载健康评估报告格式 -->
  <a-modal
    v-model:visible="form.visible"
    title="健康评估报告下载格式"
    title-align="start"
    cancel-text="取消"
    ok-text="确定"
    @ok="handleFormatOk"
    width="25%"
    modal-class="formModal"
    :mask-closable="false"
  >
    <a-form ref="formRef" :model="form">
      <a-form-item field="format" label="下载格式">
        <a-radio-group v-model="form.format">
          <a-radio value="1">Word</a-radio>
          <a-radio value="2">PDF</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { useHealthStore } from '@/store/modules/health'
import { reactive, ref, toRefs, defineEmits, onMounted, nextTick, getCurrentInstance, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { apiHealth } from '@/api/health'
import html2Canvas from 'html2canvas'
import Table from '@/components/table/index.vue'
import JsPDF from 'jspdf'
import { exportWord } from '@/utils/word'

const { proxy } = getCurrentInstance()
const { describeContent, satelliteId } = toRefs(useHealthStore())
const emit = defineEmits(['initChartData', 'refreshChart'])
const mergeTableRef = ref(null)
const descData = computed(() => {
  if (nodeForm.list.length > 0) {
    return nodeForm.list.map((item) => {
      return {
        label: item.name,
        value: item.dataInfo || '---'
      }
    })
  } else {
    return []
  }
})
const nodeForm = reactive({
  list: [],
  downloadState: false, // 是否下载评估报告
  visible: false,
  columns: [
    {
      // 表头
      title: '序号',
      width: 65,
      align: 'center'
    },
    {
      title: '整星',
      align: 'center'
    },
    {
      title: '分系统',
      align: 'center'
    },
    {
      title: '器部件',
      align: 'center'
    }
  ],
  dataList: []
})
const form = reactive({
  visible: false,
  format: '1'
})
const time = ref('')
const nodeId = ref('')
const typeCharts = ref(null)
const option = reactive({
  tooltip: {
    trigger: 'item',
    backgroundColor: '#666',
    borderColor: '#666',
    textStyle: {
      color: '#fff'
    },
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    top: '8px',
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      show: true,
      color: '#ffffff'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      show: true,
      color: '#ffffff'
    }
  },
  series: []
})
const changeTime = (data) => {
  time.value = data
}
const handleOk = () => {
  nodeForm.downloadState = true
  handleSubmit()
}
const handleSubmit = () => {
  if (!time.value) {
    Message.error('请选择日期')
    return
  }
  const data = {
    nodeId: nodeId.value,
    satelliteId: satelliteId.value,
    evaluationTime: time.value
  }
  apiHealth.evaluation(data).then((res) => {
    if (+res.code === 200) {
      Message.success('计算成功')
      if (nodeForm.downloadState) {
        nodeForm.visible = true
        nextTick(() => {
          initChart()
        })
      }
      getHealthInfo(nodeId.value)
      emit('initChartData', nodeId.value)
      emit('refreshChart')
    } else {
      Message.error(res.message)
    }
  })
}
// 下载评估报告
const handleBeforeOk = (done) => {
  if (nodeForm.dataList.length === 0 && option.xAxis.data.length === 0) {
    Message.warning('暂无健康评估数据，请重新选择！')
    return
  }
  done(false)
  nodeForm.visible = true
  form.visible = true
}
// 关闭
const handleCancel = () => {
  nodeForm.visible = false
  time.value = ''
}
const handleFormatOk = () => {
  if (form.format === '1') {
    exportWordFile()
  } else {
    getPdf()
  }
  nodeForm.visible = false
  form.visible = false
}
// 下载word文档
const exportWordFile = async () => {
  const arr = []
  if (nodeForm.dataList.length > 0) {
    nodeForm.dataList.forEach((item, index) => {
      arr.push({
        number: index + 1,
        satelliteName: item.satelliteName, // 正星
        fxtName: item.fxtName, // 分系统
        qbjName1: item.qbjName1, // 器部件
        qbjName2: item.qbjName2 // 器部件
      })
    })
  }
  const data = {
    templateTitle: '健康评估报告', // 模版标题
    satelliteName: describeContent.value?.nodeName, // 卫星名称
    evaluationTime: time.value, // 评估时间
    image: await getBase64Sync(),
    table: arr
  }
  // 控制导出的word图片大小
  const imgSize = {
    image: [596, 300]
  }
  exportWord('/healthTemplate.docx', data, '健康评估报告.docx', imgSize)
}
// html转base64
const getBase64Sync = () => {
  return new Promise((resolve) => {
    const targetDom = document.querySelector('#report-charts')
    const domScrollHeight = targetDom.scrollHeight // 获取滚动的高度
    targetDom.setAttribute('style', `height: ${domScrollHeight}px;background-color: #094c6b;`) // 把高度赋值给需要截图的那个div
    html2Canvas(targetDom, {
      allowTaint: true,
      taintTest: false,
      useCORS: true,
      dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
      scale: 4 // 按比例增加分辨率
    }).then((canvas) => {
      resolve(canvas.toDataURL())
    })
  })
}
// 下载PDF
const getPdf = () => {
  const scrollTop = document.documentElement.scrollTop
  window.pageYoffset = 0
  document.documentElement.scrollTop = 0
  document.body.scrollTop = 0
  const title = '健康评估报告' // DPF标题
  html2Canvas(document.querySelector('#pdfDom'), {
    allowTaint: true,
    taintTest: false,
    useCORS: true,
    dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
    scale: 4 // 按比例增加分辨率
  }).then(function (canvas) {
    // 截完图后再把位置滚动到之前的位置
    document.documentElement.scrollTop = scrollTop
    // 直接下载图片
    // const link = document.createElement('a') // 创建一个超链接对象实例
    // const event = new MouseEvent('click') // 创建一个鼠标事件的实例
    // link.download = title + '.png' // 设置要下载的图片的名称
    // link.href = canvas.toDataURL() // 将图片的URL设置到超链接的href中
    // link.dispatchEvent(event) // 触发超链接的点击事件
    // 下载pdf
    const contentWidth = canvas.width
    const contentHeight = canvas.height
    const pageHeight = (contentWidth / 592.28) * 841.89
    let leftHeight = contentHeight
    let position = 0
    const imgWidth = 595.28
    const imgHeight = (592.28 / contentWidth) * contentHeight
    const pageData = canvas.toDataURL('image/jpeg', 1.0)
    const PDF = new JsPDF('', 'pt', 'a4')
    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    } else {
      while (leftHeight > 0) {
        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
        leftHeight -= pageHeight
        position -= 841.89
        if (leftHeight > 0) {
          PDF.addPage()
        }
      }
    }
    PDF.save(title + '.pdf')
  })
  // window.setTimeout(() => {
  //   done(false);
  // }, 3000);
}
const getHealthInfo = (id) => {
  nodeForm.downloadState = false
  apiHealth.getHealthDeepInfo(id).then((res) => {
    if (+res.code === 200) {
      nodeForm.list = res.data?.values || []
    }
  })
}
useHealthStore().$subscribe((mutation, state) => {
  nodeId.value = state?.describeContent?.id
  getHealthInfo(nodeId.value)
})
let charts = null
const initChart = () => {
  charts = proxy.$echarts.init(typeCharts.value)
  changeChartType()
}
const changeChartType = () => {
  charts.clear()
  option.series = []
  option.xAxis.data = []
  nodeForm.dataList = []
  apiHealth.getHealthReport(satelliteId.value).then((res) => {
    if (+res.code === 200) {
      nodeForm.dataList = res.data?.tableList || []
      option.xAxis.data = res.data.chart.healthDeepTimeList || []
      option.series = [
        {
          data: res.data.chart.healthDeepData?.dataInfo || [],
          name: res.data.chart.healthDeepData?.name || '',
          type: 'line'
        }
      ]
      charts?.setOption(option)
      nextTick(() => {
        mergeTableRef.value.funUniteTable(4)
      })
    } else {
      Message.error(res.message)
    }
  })
}
onMounted(() => {
  window.addEventListener(
    'resize',
    () => {
      if (charts) {
        charts.resize()
      }
    },
    false
  )
})
</script>
<style scoped>
.arco-modal-container .formModal .arco-modal-body {
  border: solid 1px red;
  padding: 0 !important;
}

.grid {
  padding: 24px 20px;
  background-color: #094c6b;
  color: #fff;
}

.grid .arco-col-12 p {
  margin: 0;
  color: #ffffff;
  text-align: left;
}

.grid .arco-col-24 p {
  color: #ffffff;
  text-align: center;
  font-size: 16px;
}

.grid .arco-col-12 p i {
  font-style: normal;
}

#report-charts {
  width: 100%;
  height: 305px;
}
</style>
<style lang="less" scoped>
@width: 100%;
@height: 100%;
.describe {
  height: 100%;
  width: 260px;
  background-size: 100% 100%;

  .describe-card {
    width: @width;
    height: @height;
    position: relative;

    .describe-header {
      color: #10e7f7;
      font-size: 20px;
      font-weight: 500;
      height: 60px;
      text-align: center;
      line-height: 60px;
    }

    .describe-content {
      height: calc(100% - 142px);
      width: 100%;
      overflow-y: auto;

      .arco-form {
        width: auto;
        margin: 0 20px;

        .arco-form-item {
          margin-bottom: 10px;
        }
      }
    }

    .describe-footer {
      position: absolute;
      bottom: 0;
      background: #fff;

      .describe-btn {
        margin: 12px auto 0;
        width: 100px;
        background-color: #0077a9;
        color: #fff;
      }
    }
  }
}
</style>
